package com.cus.tom.transfer.frag;

import android.os.Bundle;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;

import com.cus.tom.transfer.App;
import com.cus.tom.transfer.R;
import com.cus.tom.transfer.adapter.BatchAdapter;
import com.cus.tom.transfer.bean.FileType;
import com.cus.tom.transfer.bean.MediaData;
import com.cus.tom.transfer.databinding.RecordImgBinding;
import com.cus.tom.transfer.db.RecvDao;
import com.cus.tom.transfer.db.SendDao;
import com.cus.tom.transfer.db.TransDao;
import com.cus.tom.transfer.it.ImgUi;
import com.cus.tom.transfer.utils.SaveUtils;
import com.cus.tom.transfer.utils.Utils;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.plata.base.aclr.common.ITask;
import com.plata.base.aclr.common.SilentTask;
import com.plata.base.aclr.common.TaskEngine;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

public class RecordImgFragment extends BaseFragment implements ImgUi {

    protected RecordImgBinding binding;
    BatchAdapter adapter;
    boolean working = false;
    final protected int type;
    TransDao dao;
    ITask task = null;

    public RecordImgFragment(int type) {
        this.type = type;
        dao = type == 0 ? new RecvDao() : new SendDao();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = RecordImgBinding.inflate(inflater, container, false);
        binding.includeToolbar.back.setVisibility(View.INVISIBLE);
        binding.includeToolbar.all.setOnClickListener(v -> {
            boolean bo = !binding.includeToolbar.all.isSelected();
            binding.includeToolbar.all.setSelected(bo);
            adapter.selectAll(bo);
        });
        setAdapter();

        if (type == 0) {
            binding.export.setOnClickListener(v -> {
                doExport();
            });
        } else {
            binding.export.setVisibility(View.GONE);
        }
        binding.delete.setOnClickListener(v -> {
            TipDlg dlg = new TipDlg().setMsg("删除选中记录？").setOk("删除").check(hasFile());
            dlg.setOnDismissListener(new BaseDialogFragment.OnDismissListener() {
                @Override
                public void onDismiss(boolean isOk, Object value) {
                    if (isOk) {
                        delete(value instanceof Boolean ? (Boolean) value : false);
                    }
                }
            });
            dlg.show(getChildFragmentManager(), "");
        });
        loadData();

        return binding.getRoot();
    }

    protected boolean hasFile() {
        return true;
    }

    protected void doExport() {
        LoadingDlg dlg = new LoadingDlg().setMsg("导出图片到相册");
        dlg.show(getChildFragmentManager(), "");
        if (task != null) {
            return;
        }
        List<MediaData> list = adapter.getSelect();
        task = new SilentTask("") {
            @Override
            public void runInBackground() throws Exception {
                for (MediaData d : list) {
                    saveFile(d);
                }
                h.post(() -> {
                    task = null;
                    dlg.dismiss();
                });
            }

            @Override
            public long getTimeout() {
                return 0;
            }
        };
        TaskEngine.getInstance().submit(task);
    }

    protected void saveFile(MediaData data) {
        SaveUtils.saveImgFileToAlbum(App.getApp(), data.getPath());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (task != null) {
            task.cancel();
        }
    }

    protected void setAdapter() {
        GridLayoutManager manager = new GridLayoutManager(getActivity(), 3);
        manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if (adapter.getItemViewType(position) == 0) {
                    return 3;
                }
                return 1;
            }
        });
        binding.rvAlbum.setLayoutManager(manager);
        adapter = new BatchAdapter(this, type);
        binding.rvAlbum.setAdapter(adapter);
    }

    private void delete(boolean delete) {
        List<MediaData> list = adapter.getSelect();
        if (list.isEmpty()) {
            return;
        }
        binding.bar1.setVisibility(View.VISIBLE);
        TaskEngine.getInstance().submit(new SilentTask("") {
            @Override
            public void runInBackground() throws Exception {
                List<Long> l = new ArrayList<>();
                for (MediaData item : list) {
                    l.add(item.id);
                    if (delete) {
                        Utils.deleteFile(new File(item.getPath()));
                    }
                }
                dao.delete(l);
                loadData();
            }
        });
    }

    protected List<MediaData> getMediaData() {
        if (!XXPermissions.isGranted(getActivity(), Permission.MANAGE_EXTERNAL_STORAGE)) {
            return Collections.emptyList();
        }
        return dao.getAllByType(FileType.PIC);
    }

    private boolean loadData() {
        if (working) {
            return false;
        }
        working = true;
        TaskEngine.getInstance().submit(new SilentTask("") {
            @Override
            public void runInBackground() throws Exception {
                try {
                    List<MediaData> list = getMediaData();
                    if (list == null || list.isEmpty()) {
                        h.post(() -> {
                            binding.noDataTv.setVisibility(View.VISIBLE);
                            adapter.setData(null, 0, 0, 0);
                        });
                        return;
                    }
                    h.post(() -> binding.noDataTv.setVisibility(View.GONE));
                    if (list.size() == 1 && !list.get(0).isValid) {
                        return;
                    }
                    long time = list.get(0).getAddTime();
                    int j = 0;
                    int num = 0;
                    long size = 0;
                    SparseArray<ArrayList<MediaData>> array = new SparseArray();
                    ArrayList<MediaData> l = new ArrayList();
                    l.add(list.get(0));
                    array.put(0, l);
                    for (int i = 1; i < list.size(); i++) {
                        MediaData m = list.get(i);
                        if (Utils.isSameDate(time, m.getAddTime())) {
                            l.add(m);
                        } else {
                            time = m.getAddTime();
                            ++j;
                            l = new ArrayList();
                            l.add(m);
                            array.put(j, l);
                        }
                        if (isInSelectedGroup(m) || m.isSetSelected()) {
                            ++num;
                            size += m.getSize();
                            m.setSetSelected(true);
                        }
                    }
                    if (isInSelectedGroup(list.get(0)) || list.get(0).isSetSelected()) {
                        ++num;
                        size += list.get(0).getSize();
                        list.get(0).setSetSelected(true);
                    }
                    list.clear();
                    ArrayList result = new ArrayList();
                    for (int i = 0; i < array.size(); i++) {
                        l = array.valueAt(i);
                        result.add(l.get(0).getAddTime());
                        result.addAll(l);
                    }
                    int i = num;
                    long ll = size;
                    h.post(() -> {
                        adapter.setData(result, 0, i, ll);
                    });
                } catch (Throwable e) {
                    e.printStackTrace();
                } finally {
                    h.post(() -> {
                        binding.bar1.setVisibility(View.INVISIBLE);
                        working = false;
                    });
                }
            }
        });
        return true;
    }

    private boolean isInSelectedGroup(MediaData data) {
        Set<Long> set = adapter.getSelectGroup();
        for (Long l : set) {
            if (Utils.isSameDate(l, data.getAddTime())) {
                return true;
            }
        }
        return false;
    }

    public void selectChange(int num, long size) {
        if (num <= 0) {
            binding.tip.setText(R.string.app_num0);
        } else {
            binding.tip.setText(String.format("已选择%d个文件", num));
        }
    }
}
